import { FormSchema } from '/@/components/Form/index';
import { getEntityDeviceList } from '/@/api/thingsborad/entity/entity';
import { useDebounceFn } from '@vueuse/shared';
import { UseFormReturnType, useForm, FormProps } from '/@/components/Form';
import { buildUUID } from '/@/utils/uuid';
import { ref } from 'vue';
import { getEntityKeys } from '/@/api/thingsborad/dashboards/dashboard';
const seriesParams = ref<Recordable>({
  payload: {
    entityFilter: {
      type: 'singleEntity',
      singleEntity: null,
    },
    pageLink: {
      pageSize: 100,
      page: 0,
      sortOrder: {
        key: {
          type: 'ENTITY_FIELD',
          key: 'createdTime',
        },
        direction: 'DESC',
      },
    },
  },
  query: {
    attributes: true,
    timeseries: true,
  },
});

export const schemas: FormSchema[] = [
  {
    field: 'Divider1',
    label: '数据源',
    component: 'Divider',
    colProps: {
      span: 24,
    },
  },
  {
    field: 'type',
    label: '类型',
    component: 'Select',
    componentProps: () => {
      return {
        placeholder: '请选择类型',
        allowClear: false,
        options: [
          {
            label: '设备',
            value: 'device',
          },
          {
            label: '告警',
            value: 'alarm',
          },
        ],
      };
    },
    defaultValue: 'device',
    required: true,
  },
  {
    field: 'deviceId',
    label: '设备',
    component: 'ApiSelect',
    componentProps: () => {
      const params = ref({
        pageSize: 50,
        page: 0,
        textSearch: '',
        sortProperty: 'name',
        sortOrder: 'ASC',
      });
      return {
        placeholder: '请选择设备',
        listHeight: 160,
        api: getEntityDeviceList,
        params: params.value,
        resultField: 'data',
        labelField: 'name',
        valueField: 'id',
        objectToJson: true,
        showSearch: true,
        onSearch: useDebounceFn((e) => {
          params.value.textSearch = e;
        }, 300),
        onChange: (e: string) => {
          if (e) {
            seriesParams.value.payload.entityFilter.singleEntity = JSON.parse(e);
          } else {
            params.value.textSearch = '';
          }
        },
        immediate: true,
      };
    },
    ifShow: ({ values }) => values.type === 'device',
    defaultValue: undefined,
    required: true,
  },
  {
    field: 'Divider2',
    label: '图表配置',
    component: 'Divider',
    colProps: {
      span: 24,
    },
  },
  {
    field: 'chartType',
    label: '图表类型',
    component: 'Select',
    componentProps: {
      allowClear: false,
      options: [
        {
          label: '折线图',
          value: 'line',
        },
        {
          label: '柱状图',
          value: 'bar',
        },
        {
          label: '饼图',
          value: 'pie',
        },
        {
          label: '地图',
          value: 'map',
        },
      ],
    },
    defaultValue: 'line',
    required: true,
  },
  {
    field: 'series',
    label: 'Series',
    component: 'Input',
    slot: 'seriesSlot',
    colProps: {
      span: 24,
    },
    ifShow: ({ model }) => model.deviceId,
    defaultValue: [],
  },
];
export const seriesFormSchema: FormSchema[] = [
  {
    field: 'key',
    label: '',
    component: 'ApiSelect',
    componentProps: {
      placeholder: '请选择数据键',
      listHeight: 160,
      api: getEntityKeys,
      params: seriesParams.value,
      isDashBoard: true,
      showSearch: true,
      alwaysLoad: true,
      immediate: true,
    },
    colProps: {
      span: 6,
      style: {
        marginRight: '20px',
      },
    },
  },
  {
    field: 'name',
    label: '',
    component: 'Input',
    componentProps: {
      placeholder: '请输入图例名称',
    },
    colProps: {
      span: 6,
      style: {
        marginRight: '20px',
      },
    },
  },
  {
    field: 'color',
    label: '',
    componentProps: {
      placeholder: '请输入图例颜色',
    },
    component: 'Input',
    colProps: {
      span: 6,
    },
  },
  {
    field: 'deleteBtn',
    label: '',
    component: 'Input',
    slot: 'deleteSlot',
    colProps: {
      span: 4,
      style: {
        textAlign: 'center',
      },
    },
  },
];

export type FormItem = {
  key: string;
  Form: UseFormReturnType;
};
export const baseFormConfig: Partial<FormProps> = {
  showActionButtonGroup: false,
};
export const seriesFormList: FormItem[] = [
  {
    key: buildUUID(),
    Form: useForm(Object.assign({ schemas: seriesFormSchema }, baseFormConfig) as FormProps),
  },
];

// ws第一次发送消息的处理函数
export const processingChartPublicFormData = (cmdId: number, formData: Recordable) => {
  const sendMsg = {
    cmdId,
    query: {
      pageLink: {
        pageSize: 1024,
        page: 0,
        sortOrder: {
          key: {
            type: 'ENTITY_FIELD',
            key: 'createdTime',
          },
          direction: 'DESC',
        },
      },
      entityFields: [
        {
          type: 'ENTITY_FIELD',
          key: 'name',
        },
        {
          type: 'ENTITY_FIELD',
          key: 'label',
        },
        {
          type: 'ENTITY_FIELD',
          key: 'additionalInfo',
        },
      ],
      latestValues: [],
      entityFilter: {
        type: 'singleEntity',
        singleEntity: JSON.parse(formData.deviceId),
      },
    },
  };
  return {
    entityDataCmds: [sendMsg],
  };
};
// ws第二次发送消息的处理函数
export const processingChartPrivateFormData = (cmdId: number, formData: Recordable) => {
  const keys: string[] = [];
  let sendMsg: Recordable = {};
  if (formData.chartType === 'line' || formData.chartType == 'bar') {
    formData.series.forEach((item: Recordable) => {
      keys.push(JSON.parse(item.key).key);
    });
    sendMsg = {
      cmdId,
      historyCmd: {
        keys,
        startTs: 1710926571020,
        endTs: 1713518571020,
        interval: 7200000,
        limit: 200,
        agg: 'NONE',
      },
    };
  }
  return {
    entityDataCmds: [sendMsg],
  };
};

// ws第二次获得数据的处理函数
export const processingChartPrivateReceiveData = (data: Recordable, formData: Recordable) => {
  let legendKeys: string[] = [];
  const series: Recordable[] = [];
  let partOptions: Recordable = {};
  if (formData.chartType == 'line' || formData.chartType == 'bar') {
    if (data.update) {
      // 图例数组
      legendKeys = Object.keys(data.update[0].timeseries);
      // 图例对应数据
      formData.series.forEach((item: Recordable) => {
        const seriesData: string[][] = [];
        data.update[0].timeseries[JSON.parse(item.key).key].forEach((item: Recordable) => {
          seriesData.push(Object.values(item));
        });
        series.push({
          name: JSON.parse(item.key).key,
          data: seriesData,
          type: formData.chartType,
          itemStyle: {
            color: item.color,
          },
        });
      });
    }
    partOptions = {
      legend: {
        type: 'scroll',
        left: 10,
        data: legendKeys,
      },
      series,
    };
  } else if (formData.chartType == 'pie') {
    if (data.data) {
    }
  }
  return partOptions;
};
